/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.myself;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;

import java.math.BigDecimal;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.FragmentStackActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.global.DanluApplication;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.fragment.AccountInfoFragment;
import cn.com.dhc.danlu.fragment.InputPhoneActiveFragment;
import cn.com.dhc.danlu.fragment.SelectActiveFragment;
import cn.com.dhc.danlu.fragment.UnBindOrActiveNewPhoneFragment;
import cn.com.dhc.danlu.fragment.bridge.FragmentBridge;
import cn.com.dhc.danlu.fragment.bridge.FragmentBridge.OnFragmentBrigdeListener;
import cn.com.dhc.danlu.util.ActivePhoneProcess;
import cn.com.dhc.danlu.util.ActivityUtils;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.DLToolbar;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.hd.mall.web.webservices.entity.request.account.ActivatePhoneRequest;
import cn.com.hd.mall.web.webservices.entity.request.account.GetAcctInfoRequest;
import cn.com.hd.mall.web.webservices.entity.request.regist.VerificationCodeRequest;
import cn.com.hd.mall.web.webservices.entity.response.login.LoginResponse;
import cn.com.hd.mall.web.webservices.entity.response.mydl.account.ActivatePhoneResponse;
import cn.com.hd.mall.web.webservices.entity.response.mydl.account.GetAcctInfoResponse;
import cn.com.hd.mall.web.webservices.entity.response.mydl.account.GetValCodeForActivateResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 吴海洋(<a href="mailto:wuhaiyang@danlu.com">wuhaiyang@danlu.com</a>)<br/>
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2016-11-07 04:23<br/>
 *
 * <p>
 * 我的账号页面
 * </p>
 */
public class MyAccountActivity extends FragmentStackActivity implements OnFragmentBrigdeListener {
    /**
     * 账户信息fragment
     */
    private AccountInfoFragment mAccountInfoFragment;
    /**
     * 激活手机号fragment
     */
    private InputPhoneActiveFragment mInputPhoneFragment;

    // private DanluTaskProxy danluTaskProxy;
    private String verifiCode;  // 验证码
    private String phoneNum;

    private boolean isGetAccountInfoSuc = false;
    private boolean isJumpFromLogin = false;
    /**
     * 是否强制激活标志位
     */
    private boolean isForceActive;
    private boolean isSwitchActiveFragment = false;

    @Override
    public void onHandle(int type, Object obj) {
        if (type == FragmentBridge.TYPE_GET_ACCOUNT_INFO) {
            // 获取账户详情
            getUserAccountInfo();
        } else if (type == FragmentBridge.TYPE_PHONE_ACTION) {
            // 账户fragment 点击手机号item 事件触发
            if (isGetAccountInfoSuc) {
                if (!mAccountInfoFragment.isActive()) {
                    // 未激活跳转到激活手机号fragment
                    goActivePhoneFragment();
                } else {
                    // 当前已经激活了 执行解除绑定手机号流程 用户选择 - > 解绑原手机号 ——>激活新手机
                    switchFragment(new SelectActiveFragment(), getResources().getString(R.string.select_remove_bind));
                }
            } else {
                getUserAccountInfo();
            }
        } else if (type == FragmentBridge.TYPE_GET_CODE) {
            // 请求获取短信验证码 （未包含图像验证码）
            String phone = (String) obj;
            getSmsCode(phone);
        } else if (type == FragmentBridge.TYPE_VERIFY_CODE) {
            String smsCode = (String) obj;
            verifySmsCode(smsCode);
        } else if (type == FragmentBridge.TYPE_GO_REMOVE_BIND) {
            // 跳转到解绑原来手机号fragment
            UnBindOrActiveNewPhoneFragment fragment = UnBindOrActiveNewPhoneFragment.newInstance(phoneNum, true);
            //            fragment.setDanluTaskProxy(danluTaskProxy);
            switchFragment(fragment, getResources().getString(R.string.modify_bind_phone));
        } else if (type == FragmentBridge.TYPE_GO_BIND_NEWPHONE) {
            UnBindOrActiveNewPhoneFragment fragment = UnBindOrActiveNewPhoneFragment.newInstance(null, false);
            //            fragment.setDanluTaskProxy(danluTaskProxy);
            switchFragment(fragment, "激活新手机");
        } else if (type == FragmentBridge.TYPE_ACTIVE_NEWPHONE_SUC) {
            // 多个fragment 需要出栈 最好调用popBackStackImmediate 清理所有任务栈
            clearSameTopStack(SelectActiveFragment.class.getSimpleName());
        }
    }

    /**
     * 获取用户账号详情信息
     */
    public void getUserAccountInfo() {
        GetAcctInfoRequest request = new GetAcctInfoRequest();
        request.setUserId(agent.getLoginUser().getUserId());
        request.setToken(agent.getToken());
        request.setUserAcct(agent.getLoginUser().getUserAcct());
        agent.getApi().getUserAccountInfo(request).compose(OperatorUtils.<GetAcctInfoResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetAcctInfoResponse>(MyAccountActivity.this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(GetAcctInfoResponse getAcctInfoResponse) {
                        isGetAccountInfoSuc = true;
                        phoneNum = getAcctInfoResponse.getTel();
                        mAccountInfoFragment.refreshInfo(getAcctInfoResponse);
                        //刷新下全局内存
                        agent.getLoginUser().setTelStatus(getAcctInfoResponse.getTelStatus());
                        if (!TextUtils.isEmpty(getAcctInfoResponse.getTelStatus()) && !getAcctInfoResponse.getTelStatus().equals("0") && isForceActive) {
                            mToolbar.setBackVisible(false);
                        }
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        return "";
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "账号信息获取失败！" : displayMessage);
                    }
                });
    }

    public void goActivePhoneFragment() {
        mInputPhoneFragment = InputPhoneActiveFragment.newInstance(phoneNum);
        switchFragment(mInputPhoneFragment, R.id.fl_fragment_container, "激活手机号");
    }

    /**
     * 请求获取短信验证码
     */
    private void getSmsCode(String phone) {
        VerificationCodeRequest request = new VerificationCodeRequest();
        request.setTel(phone);
        request.setToken(agent.getToken());
        agent.getApi().getSmsCodeActivePhone(request).compose(OperatorUtils.<GetValCodeForActivateResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetValCodeForActivateResponse>(MyAccountActivity.this, R.string.tips_get_sms_code) {
                    @Override
                    protected void onSuccess(GetValCodeForActivateResponse getValCodeForActivateResponse) {
                        verifiCode = getValCodeForActivateResponse.getValCode();
                        ToastUtil.getInstance().show("验证码发送成功");
                        mInputPhoneFragment.setDisAllowInputPhone(false);
                        //开始倒计时
                        mInputPhoneFragment.startTimer();
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        String displayMsg = "";
                        switch (code) {
                            case "1":
                                displayMsg = DanluApplication.get().getString(R.string.consignee_tel_not_right);
                                break;
                            case  "4":
                                displayMsg = DanluApplication.get().getString(R.string.interval_lessthan);
                                break;
                            default:
                                displayMsg = DanluApplication.get().getString(R.string.send_sms_error);
                                break;
                        }
                        return displayMsg;
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        mInputPhoneFragment.reGetSmsCode();
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
        phoneNum = phone;
    }

    /**
     * 校验短信验证码
     */
    private void verifySmsCode(String smsCode) {
        if (TextUtils.isEmpty(verifiCode)) {
            ToastUtil.getInstance().show("请获取验证码");
            return;
        }
        if (!smsCode.equals(verifiCode)) {
            mInputPhoneFragment.setDisAllowInputPhone(true);
            ToastUtil.getInstance().show("验证码错误，请重新输入");
            return;
        }
        LoginResponse loginUser = agent.getLoginUser();
        // 验证码输入正确 请求服务器激活手机号码
        ActivatePhoneRequest request = new ActivatePhoneRequest();
        request.setToken(agent.getToken());
        request.setUserId(loginUser.getUserId());
        if (TextUtils.isEmpty(loginUser.getFirstActiveTime()) && loginUser.getTelStatus().equals("1")) {
            // 未激活 且 送钱 满足
            request.setConditionInd("1");
        } else {
            request.setConditionInd("0");
        }
        request.setTel(phoneNum);
        request.setUserAcct(agent.getLoginUser().getUserAcct());
        //add by llq
        agent.getApi().activePhone(request).compose(OperatorUtils.<ActivatePhoneResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<ActivatePhoneResponse>(MyAccountActivity.this, R.string.tips_active_phone) {
                    @Override
                    protected void onSuccess(ActivatePhoneResponse activatePhoneResponse) {
                        showAlertDialog(activatePhoneResponse);
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        String diaplayMsg = "";
                        switch (code) {
                            case "1":
                                diaplayMsg = getString(R.string.tips_activate_failed);
                                break;
                            case "2":
                                diaplayMsg = getString(R.string.tips_phone_num_activated);
                                break;
                            default:
                                break;
                        }
                        return diaplayMsg;
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? getString(R.string.tips_activate_failed) : displayMessage);
                    }
                });
    }

    private void clearSameTopStack(String className) {
        int before = getSupportFragmentManager().getBackStackEntryCount();
        getSupportFragmentManager().popBackStackImmediate(className, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        int now = getSupportFragmentManager().getBackStackEntryCount();
        int diff = before - now;
        int titleSize = mTitles.size();
        for (int i = titleSize - 1; i >= titleSize - diff; i--) {
            mTitles.remove(i);
        }
        String string = mTitles.get(mTitles.size() - 1);
        mToolbar.setTitle(string);
    }

    protected void showAlertDialog(ActivatePhoneResponse model) {
        String ind = model.getCouponInd();
        String tips;
        if (ind.equals("0")) {
            // 无红包
            tips = "手机号已经激活";
        } else {
            // 有红包
            String amt = CommonUtils.fenToYuan(new BigDecimal(model.getCouponAmt())).toPlainString();
            tips = "手机号已经激活，" + amt + "元红包领取成功，请五分钟后到我的红包查看!";
        }
        new ViewDialog.Builder(this).setMessage(tips).setCancelable(false)
                .setPositiveButton(R.string.btn_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        reverseAction();
                    }
                }).create().show();
        agent.getLoginUser().setTelStatus("0");
    }

    protected void reverseAction() {
        if (isJumpFromLogin) {
            handleLoginSituationAction();
        } else {
            finish();
        }
    }

    private void handleLoginSituationAction() {
        // 跳转到首页画面
        //        ActivityUtils.startMainMenuActivity(delegate.getContext());
        ActivityUtils.startMainMenuActivity(MyAccountActivity.this);
        // 本画面结束
        finish();
    }

    @Override
    protected void onCreate(Bundle saveInstance) {
        super.onCreate(saveInstance);
        setContentView(R.layout.activity_my_account);

        mToolbar = (DLToolbar) findViewById(R.id.toolbar);
        if (null != saveInstance) {
            isForceActive = saveInstance.getBoolean("isForceActive");
            isJumpFromLogin = saveInstance.getBoolean("isFromLogin");
            isSwitchActiveFragment = saveInstance.getBoolean("isSwitchActiveFragment");
        } else {
            isForceActive = getIntent().getBooleanExtra("isForceActive", false);
            isJumpFromLogin = getIntent().getBooleanExtra("isFromLogin", false);
            isSwitchActiveFragment = getIntent().getBooleanExtra("isSwitchActiveFragment", false);
        }

        if (isForceActive && !isCurrentAccountActive()) {
            mToolbar.setBackVisible(false);
        } else {
            mToolbar.setBackListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    backLogic();
                }
            });
        }
        if (isSwitchActiveFragment) {
            String phone = agent.getLoginUser().getTel();
            mInputPhoneFragment = InputPhoneActiveFragment.newInstance(phone);
            addDefaultFragment(mInputPhoneFragment, R.id.fl_fragment_container, "激活手机号");
            ActivePhoneProcess.isShowBefore = true;
        } else {
            // 添加默认展示信息的fragment
            mAccountInfoFragment = new AccountInfoFragment();
            addDefaultFragment(mAccountInfoFragment, R.id.fl_fragment_container, "我的账号");
        }
    }

    /**
     * 重写按下左上角返回键的 的时候切换fragment
     */
    @Override
    protected void backPressed() {
        backLogic();
    }

    @Override
    public void onBackPressed() {
        if (!isCurrentAccountActive() && isForceActive) {
            return;
        }
        backLogic();
        // 强制激活 禁用后退键
    }

    private boolean isCurrentAccountActive() {
        boolean isCurrentUserActive = false;
        if (agent.getLoginUser() != null) {
            isCurrentUserActive = agent.getLoginUser().getTelStatus().equals("0");
        }
        return isCurrentUserActive;
    }

    /**
     * 暂未继承父类返回逻辑实现
     */
    protected void backLogic() {
        int stackEntryCount = mFragmentManager.getBackStackEntryCount();
        if (stackEntryCount >= 1) {
            if (stackEntryCount >= 3) {
                clearSameTopStack(UnBindOrActiveNewPhoneFragment.class.getSimpleName());
                return;
            }
            getSupportFragmentManager().popBackStack();
            changeTitle(stackEntryCount);
        } else {
            if (isJumpFromLogin) {
                handleLoginSituationAction();
            } else {
                finish();
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("phone", phoneNum);
        outState.putBoolean("isForceActive", isForceActive);
        outState.putBoolean("isSwitchActiveFragment", isSwitchActiveFragment);
        outState.putBoolean("isFromLogin", isJumpFromLogin);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        phoneNum = savedInstanceState.getString("phone");
        isForceActive = savedInstanceState.getBoolean("isForceActive");
        isSwitchActiveFragment = savedInstanceState.getBoolean("isSwitchActiveFragment");
    }
}